const { mysql } = require('../qcloud')
const jsonwebtoken = require('jsonwebtoken')
const myws = require('../mywebsocket')

/**
 * @api {post} /login Login
 * @apiName login
 * @apiGroup User
 *
 * @apiParam {String} mobilePhone Users unique ID.
 * @apiParam {String} password Users password.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
async function login(ctx, next) {
    const body = ctx.request.body;
    await mysql.select('*').where({ mobilePhone: body.mobilePhone, password: body.password }).limit(1).from('user').then(res => {

        if (res.length > 0) {
            var data = res[0]
            const token = jsonwebtoken.sign({ userId: data.id }, 'jwt dome')
            console.log("token: " + token)
            data["token"] = token
            mysql.table("user").where({ id: data.id }).update({ token }).then((data) => {
                console.log("chengg" + data)
            }).catch(err => {
                console.log("失败" + err)
            })
            ctx.state.data = data
            ctx.state.message = "登录成功"
        } else {
            ctx.state.code = 200
            ctx.state.data = { message: "用户名或密码错误" }
        }

    }).catch(err => {
        ctx.state.code = 200
        ctx.state.data = { message: err }
    })

}

/**
 * @api {post} /register Register
 * @apiName register
 * @apiGroup User
 *
 * @apiParam {String} nickname Nickname for user.
 * @apiParam {String} mobilePhone MobilePhone for user.
 * @apiParam {String} avatorUrl AvatorUrl for user.
 * @apiParam {String} password Password for user.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
registe = async (ctx, next) => {

    const body = ctx.request.body;
    body.createdAt = new Date()
    await mysql.insert(body, 'id').into('user')
        .then((res) => {
            ctx.state.message = "注册成功"
            ctx.state.data = Object.assign({ id: res[0] }, body)

            console.log(res)
        }).catch(err => {
            ctx.state.message = "注册失败"
            ctx.state.data = err

        })
    console.log(body)


}

/**
 * @api {post} /friendRequest FriendRequest
 * @apiName friendRequest
 * @apiGroup User
 *
 * @apiParam {String} fromUserId UserId for from user.
 * @apiParam {String} toUserId UserId for to user.
 * @apiParam {String} message Message.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
friendRequest = async (ctx, next) => {

    const body = ctx.request.body;
    if (!body.toUserId) {
        throw (new Error('参数有误'))
    }
    const { token } = ctx.request.header
    var payload = jsonwebtoken.verify(token, 'jwt dome')
    await mysql.select("*").where({ id: payload.userId, token }).from("user").then(res => {
        if (res.length > 0) {
            return mysql.select("*").where({ id: body.toUserId }).from('user').then(res1 => {
                if (res1.length > 0) {
                    ctx.state.data = { message: '成功发送' }
                    const token = jsonwebtoken.sign({ fromUserId: payload.userId, toUserId: body.toUserId }, 'jwt dome')
                    myws.send(JSON.stringify(
                        {
                            "fromUserId": payload.userId, fromUserName: res[0].nickname, fromUserAvator: res[0].avatorUrl,
                            "toUserId": body.toUserId, toUserName: res1[0].nickname, toUserAvator: res1[0].avatorUrl, "message": body.message, type: "FriendRequest", extras: { token: token }
                        }
                    ))
                    console.log(JSON.stringify(
                        {
                            "fromUserId": payload.userId, fromUserName: res[0].nickname, fromUserAvator: res[0].avatorUrl,
                            "toUserId": body.toUserId, toUserName: res1[0].nickname, toUserAvator: res1[0].avatorUrl, "message": body.message, type: "FriendRequest", extras: { token: token }
                        }
                    ))

                }
            })
        } else {
            ctx.state.data = { message: '验证失败' }
        }

    }).catch(err => {
        ctx.state.data = err
    })
}

/**
 * @api {post} /addFriend AddFriend
 * @apiName register
 * @apiGroup User
 *
 * @apiParam {String} nickname Nickname for user.
 * @apiParam {String} mobilePhone MobilePhone for user.
 * @apiParam {String} avatorUrl AvatorUrl for user.
 * @apiParam {String} password Password for user.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
addFriend = async (ctx, next) => {

    const body = ctx.request.body;
    const { token } = ctx.request.header


    var { userId } = jsonwebtoken.verify(token, 'jwt dome')

    var { fromUserId } = jsonwebtoken.verify(body.token, 'jwt dome')
    if (userId == fromUserId) {
        ctx.state.data = { message: "你不能添加自己为好友" }
    } else {
        await mysql.select("*").where({ fromUserId: userId, toUserId: fromUserId }).orWhere({ fromUserId, toUserId: userId }).from('friend')
            .then((res) => {

                if (res.length > 0) {
                    ctx.state.code = 200
                    ctx.state.data = {}
                    ctx.state.data["message"] = "你们已经是好友了"
                    //ctx.state.data = Object.assign({ id: res[0] }, body)
                } else {

                    return mysql.insert([{ fromUserId, toUserId: userId }, { fromUserId: userId, toUserId: fromUserId }], 'id').into('friend')
                        .then((res) => {
                            ctx.state.data = {}
                            ctx.state.data["message"] = "成功添加好友"
                            console.log(res)
                        }).catch(err => {
                            ctx.state.data["message"] = "添加好友失败"
                            ctx.state.data = err

                        })
                }

            }).catch(err => {
                ctx.state.message = "添加好友失败"
                ctx.state.data = err

            })
    }

}




/**
 * @api {post} /getFriendList 获取好友列表
 * @apiName register
 * @apiGroup User
 *
 * @apiParam {String} nickname Nickname for user.
 * @apiParam {String} mobilePhone MobilePhone for user.
 * @apiParam {String} avatorUrl AvatorUrl for user.
 * @apiParam {String} password Password for user.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
getFriendList = async (ctx, next) => {

    const body = ctx.request.body;
    const { token } = ctx.request.header


    var { userId } = jsonwebtoken.verify(token, 'jwt dome')
    // await mysql.select('*').where({ fromUserId: userId }).orWhere({ toUserId: userId })
    //     .from('friend')
    //     .then(res => {
    //         var friends = res.map((ele) => {
    //             return ele.fromUserId == userId ? ele.toUserId : ele.fromUserId
    //         })

    //         return mysql.select('*').whereIn('id', friends)
    //             .from('user')
    //             .then(res => {
    //                 // var friends = res.map((ele) => {
    //                 //     return ele.fromUserId == userId ? ele.toUserId : ele.fromUserId
    //                 // })

    //                 ctx.state.code = 200
    //                 ctx.state.data = res
    //             })
    //         ctx.state.code = 200
    //         ctx.state.data = friends
    //     })

    await mysql.select("user.*", "friend.note").where({ 'friend.fromUserId': userId })
        .from('friend').join('user', 'user.id', 'friend.toUserId')
        .then((res) => {

            var friends = res.map((ele) => {
                delete ele.token
                return ele
            })
            ctx.state.data = friends

        }).catch(err => {
            ctx.state.message = "获取好友列表失败"
            ctx.state.data = err

        })

}



/**
 * @api {get} /searchUserByMobilePhone 搜索用户
 * @apiName register
 * @apiGroup User
 *
 * @apiParam {String} nickname Nickname for user.
 * @apiParam {String} mobilePhone MobilePhone for user.
 * @apiParam {String} avatorUrl AvatorUrl for user.
 * @apiParam {String} password Password for user.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
searchUserByMobilePhone = async (ctx, next) => {
    const body = ctx.query
    await mysql.select("*").where({ 'mobilePhone': body.key })
        .from('user')
        .then((res) => {

            if (res.length > 0) {
                var user = res[0]
                delete user.token
                ctx.state.data = user
            } else {
                ctx.state.code = 200
                ctx.state.data = { message: '用户不存在' }
            }


        }).catch(err => {
            throw (err)

        })
}

/**
 * @api {get} /searchUserByMobilePhone 搜索用户
 * @apiName register
 * @apiGroup User
 *
 * @apiParam {String} nickname Nickname for user.
 * @apiParam {String} mobilePhone MobilePhone for user.
 * @apiParam {String} avatorUrl AvatorUrl for user.
 * @apiParam {String} password Password for user.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
searchUserByUserId = async (ctx, next) => {
    const body = ctx.query
    await mysql.select("*").where({ 'id': body.key })
        .from('user')
        .then((res) => {

            if (res.length > 0) {
                var user = res[0]
                delete user.token
                ctx.state.data = user
            } else {
                ctx.state.code = 200
                ctx.state.data = { message: '用户不存在' }
            }


        }).catch(err => {
            throw (err)

        })
}





async function wxlogin(ctx, next) {
    // 通过 Koa 中间件进行登录之后
    // 登录信息会被存储到 ctx.state.$wxInfo
    // 具体查看：
    console.log('Login')
    if (ctx.state.$wxInfo.loginState) {
        ctx.state.data = ctx.state.$wxInfo.userinfo
        ctx.state.data['time'] = Math.floor(Date.now() / 1000)
    }
}

// 登录授权接口
module.exports = {
    login,
    registe,
    wxlogin,
    friendRequest,
    addFriend,
    getFriendList,
    searchUserByMobilePhone,
    searchUserByUserId
}
